#!/bin/bash
# Setup script for the Dynamic MCP system

echo "============================================"
echo "Dynamic MCP Client Setup"
echo "============================================"

# Check for Python
if command -v python3 &>/dev/null; then
    PYTHON="python3"
elif command -v python &>/dev/null; then
    PYTHON="python"
else
    echo "Error: Python is not installed. Please install Python 3.6+ and try again."
    exit 1
fi

echo "Using Python: $($PYTHON --version)"

# Create a virtual environment
echo -e "\nCreating a virtual environment..."
$PYTHON -m venv venv

# Activate the virtual environment
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
    # Windows
    source venv/Scripts/activate
else
    # Linux or macOS
    source venv/bin/activate
fi

# Install required packages
echo -e "\nInstalling required packages..."
pip install flask requests sseclient-py

# Create directories
echo -e "\nCreating directories..."
mkdir -p data

# Check if Ollama is installed
echo -e "\nChecking for Ollama..."
if command -v ollama &>/dev/null; then
    echo "Ollama is already installed."
else
    echo "Ollama is not installed. Please install Ollama from https://ollama.ai/"
    echo "After installing, run: ollama pull llama3.2"
fi

# Create a run script
echo -e "\nCreating run scripts..."

# Create server run script
cat > run_server.sh << 'EOF'
#!/bin/bash
# Activate virtual environment
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
    source venv/Scripts/activate
else
    source venv/bin/activate
fi
# Run the MCP server
python dynamic_mcp_server.py --port 3000
EOF

# Create client run script
cat > run_chat.sh << 'EOF'
#!/bin/bash
# Activate virtual environment
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
    source venv/Scripts/activate
else
    source venv/bin/activate
fi
# Run the MCP chat interface
python mcp_chat.py --verbose
EOF

# Make scripts executable
chmod +x run_server.sh
chmod +x run_chat.sh

echo -e "\n============================================"
echo "Setup complete!"
echo "============================================"
echo ""
echo "To start the system:"
echo ""
echo "1. Start the MCP server in one terminal:"
echo "   ./run_server.sh"
echo ""
echo "2. Start the chat interface in another terminal:"
echo "   ./run_chat.sh"
echo ""
echo "Make sure Ollama is running with llama3.2 model."
echo "If you haven't pulled llama3.2 yet, run: ollama pull llama3.2"
echo "============================================"
